package net.jcip.chapter4;

import java.util.*;
import java.util.concurrent.*;
import java.awt.*;
import java.awt.Point;

import net.jcip.annotations.*;

/**
 * DelegatingVehicleTracker
 * <p/>
 * Delegating thread safety to a ConcurrentHashMap
 *
 * @author Brian Goetz and Tim Peierls
 */
@ThreadSafe
public class DelegatingVehicleTracker {

    //将 thread safe  委托给  ConcurrentMap
    private final ConcurrentMap<String, Point> locations;

    private final Map<String, Point> unmodifiableMap;

    private DelegatingVehicleTracker(Map<String, Point> points) {
        locations = new ConcurrentHashMap<>(points);
        unmodifiableMap = Collections.unmodifiableMap(locations);
    }

    private Map<String, Point> getLocations() {
        return unmodifiableMap;
    }

    public Point getLocation(String id) {
        return locations.get(id);
    }

    public void setLocation(String id, int x, int y) {
        if (locations.replace(id, new Point(x, y)) == null)
            throw new IllegalArgumentException("invalid vehicle name: " + id);
    }

    // Alternate version of getLocations (Listing 4.8)
    public Map<String, Point> getLocationsAsStatic() {
        return Collections.unmodifiableMap(new HashMap<>(locations));
    }

    public static void main(String[] args) throws InterruptedException {


        ConcurrentHashMap<String, Point> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 100; i++) {

            int j = i;
            Constant4.executorService.execute(() -> {
                Point point = new Point();
                point.setLocation(j, j);
                map.put("线程" + j, point);
                Constant4.countDownLatch.countDown();
            });
        }

        Constant4.countDownLatch.await(10, TimeUnit.SECONDS);
        Constant4.executorService.shutdown();
        DelegatingVehicleTracker delegatingVehicleTracker = new DelegatingVehicleTracker(map);


        Map<String, Point> locations = delegatingVehicleTracker.getLocations();

        System.out.println(locations);

    }


}

